package com.jsoft.jsofted.framework.interceptor;

import com.jsoft.jsofted.framework.utils.CocException;
import com.jsoft.jsofted.framework.utils.ObjectUtils;
import com.jsoft.jsofted.framework.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedList;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class CocExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseModel handleVaildException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        //获取校验的错误结果
//        Map<String,String > map = new HashMap<>();
        List<String> list = new LinkedList<>();
        bindingResult.getFieldErrors().forEach(item -> {
            String message = item.getDefaultMessage();
//            String field = item.getField();
//            map.put(field,message);
            list.add(message);
        });


        return ResponseModel.makeError(ObjectUtils.join(list, "\n"));
    }

    @ResponseBody
    @ExceptionHandler(Throwable.class)
    public ResponseModel handleException(Exception e) {
        String msg = this.msg(e);

        int errorCode = 0;
        if (e instanceof CocException) {
            errorCode = ((CocException) e).getErrorCode();
        }

        return ResponseModel.makeError(msg, errorCode);
    }

    private String msg(Throwable e) {
        e = root(e);
        String msg = e.getMessage();
        msg = this.translateError(msg);
        Class cls = e.getClass();
        if (cls.equals(NullPointerException.class)) {
            log.error("服务器错误：空指针！", e);
            return "服务器错误：空指针！";
        } else if (cls.equals(IndexOutOfBoundsException.class)) {
            log.error("服务器错误：数组越界！", e);
            return "服务器错误：数组越界！";
        } else {
            if (msg == null || msg.trim().length() == 0) {
                log.error("服务器错误！", e);
                return "服务器错误！";
            } else {
                return msg;
            }
        }
    }

    private Throwable root(Throwable t) {
        while (true) {
            if (t.getCause() == null)
                break;
            t = t.getCause();
        }

        return t;
    }

    private String translateError(String msg) {
        if (msg == null) {
            return msg;
        }

        if (msg.indexOf("Duplicate entry") > -1) {
            if (msg.indexOf("actable_uni_tenant_id_tel") > -1)
                return "电话号码不允许重复！您输入的电话号码可能被占用了。";
        }

        return msg;
    }
}